package array;

/**
 * 位运算优化版
 */
public class NextGeneration2 {

    public static int[][] nextGeneration(int[][] grid) {

        int height = grid.length;
        int widht = grid[0].length;

        // 计算grid[row][col]的活邻居数量
        class NeighborCounter {

            int countLiveNeighbors(int row, int col) {
                int count = 0;
                // 检查8个方向的邻居
                for (int i = -1; i <= 1; i++) {
                    for (int j = -1; j <= 1; j++) {
                        if (i == 0 && j == 0) {
                            continue;
                        }
                        int newRow = row + i;
                        int newCol = col + j;
                        // 检查边界
                        if (newRow >= 0 && newRow < height && newCol >= 0 && newCol < widht)
                            count += grid[newRow][newCol] & 1;
                    }
                }

                return count;
            }
        }

        NeighborCounter counter = new NeighborCounter();
        for (int row = 0; row < height; row++) {
            for (int col = 0; col < widht; col++) {
                // 根据游戏规则计算当前细胞状态
                int liveNeighbors = counter.countLiveNeighbors(row, col);
                // 计算当前细胞状态
                int currentCell = grid[row][col] & 1;
                if (currentCell == 1) {
                    if (liveNeighbors == 2 || liveNeighbors == 3) {
                        // 将第二位设置为1(0b10),表示下代是活细胞
                        grid[row][col] |= 2;
                    }
                    // 其他情况，细胞默认死亡，第二位保持0
                } else {
                    if (liveNeighbors == 3) {
                        // 将第二位设置为1(0b10),表示下代是活细胞
                        grid[row][col] |= 2;
                    }
                }
            }

        }

        // 遍历每个细胞，将下一代状态移动到当前位
        for (int row = 0; row < height; row++) {
            for (int col = 0; col < widht; col++) {
                grid[row][col] >>= 1;
            }
        }
        return grid;
    }
}
